<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>编辑excel</title>
    <link rel="stylesheet" href="../../static/plugins/css/pluginsCss.css" />
    <link rel="stylesheet" href="../../static/plugins/plugins.css" />
    <link rel="stylesheet" href="../../static//plugins/css/luckysheet.css" />
    <link rel="stylesheet" href="../../static/plugins/css/iconfont.css" />
    <script src="../../static/plugins/js/jquery.min.js"></script>
    <script src="../../static/plugins/js/plugin.js"></script>
    <script src="../../static/plugins/js/luckysheet.umd.js"></script>
    <script src="../../static/plugins/js/luckyexcel.umd.js"></script>
    <script src="../../static/plugins/js/uni-webview.js"></script>
    <script src="../../static/plugins/js/exceljs.min.js"></script>
    <style>
      .hiddenmask {
        display: none !important;
      }
      .showmask {
        display: flex !important;
      }
      .confirm-title {
        text-align: center;
        height: 40px;
        line-height: 40px;
      }
      .confirm-content {
        display: flex;
        align-items: center;
        justify-content: center;
        height: calc(100% - 80px);
      }
      #bottom {
        position: absolute;
        bottom: 0;
        display: flex;
        justify-content: space-around;
        width: 100%;
        height: 40px;
        line-height: 40px;
        border-top: #ccc 1px solid;
      }
      #cancel {
        color: orange;
      }
      #save {
        color: blueviolet;
      }
    </style>
  </head>
  <body>
    <div
      id="luckysheet"
      style="
        margin: 0px;
        padding: 0px;
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0px;
        top: 0px;
      "
    ></div>
    <div
      id="mask"
      class="hiddenmask"
      style="
        top: 0;
        left: 0;
        position: absolute;
        z-index: 100;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);
        display: flex;
        align-items: center;
        justify-content: center;
      "
    >
      <div
        style="
          width: 80%;
          border-radius: 10px;
          height: 200px;
          background-color: #fff;
          position: relative;
        "
      >
        <div class="confirm-title">提示</div>
        <div class="confirm-content">请确认是否保存并退出当前操作界面</div>
        <div id="bottom">
          <span id="cancel">直接退出</span>
          <span id="save">保存退出</span>
        </div>
      </div>
    </div>

    <script>
      const LuckysheetMapper = {
        border: {
          styleMapper: {
            0: "none",
            1: "thin",
            2: "hair",
            3: "dotted",
            4: "dashDot", // 'Dashed',
            5: "dashDot",
            6: "dashDotDot",
            7: "double",
            8: "medium",
            9: "mediumDashed",
            10: "mediumDashDot",
            11: "mediumDashDotDot",
            12: "slantDashDot",
            13: "thick",
          },
          positionMapper: {
            l: "left",
            r: "right",
            t: "top",
            b: "bottom",
          },
        },
      };

      // 将arraybuffer数据转为base64
      function arrayBufferToBase64(buffer) {
        var binary = "";
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
      }
      var prefix = "";
      // 将base64的数据转为blob数据
      function base64toBlob(base64, type = "application/octet-stream") {
        var dataArr = base64.split("base64,");
        prefix = dataArr[0] + "base64,";
        var data = dataArr[1];
        const bstr = atob(data);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type });
      }

      var wantype = "";
      // uniapp -->  h5的交互过程
      window.getFileType = function (data) {
        wantype = data.type;
        if (!wantype) {
          alert("当前文件没有文件类型，请联系管理员");
        }
      };

      window.doExit = function () {
        document.getElementById("mask").setAttribute("class", "showmask");
        uni.postMessage({
          data: {
            type: "innerexit",
          },
        });
      };

      // uniapp -->  h5的交互过程
      window.getFileData = function (data) {
        var wandata = "";
        try {
          wandata = base64toBlob(data, wantype);
        } catch (error) {
          alert(error);
        }

        LuckyExcel.transformExcelToLucky(
          wandata,
          function (exportJson, luckysheetfile) {
            try {
              var options = {
                container: "luckysheet", //luckysheet为容器id
                showinfobar: false,
                showtoolbar: false,
                // showsheetbar: false,
                showstatisticBar: false,
                sheetFormulaBar: false,
                columnHeaderHeight: 0,
                rowHeaderWidth: 0,
                data: exportJson.sheets,
              };
              luckysheet.create(options);
            } catch (error) {
              uni.postMessage({
                data: {
                  type: "cancel",
                },
              });
            }
          },
          function (err) {
            alert(err);
          }
        );
      };

      window.saveFileData = function () {
        doDownload();
      };

      function doDownload() {
        // 1. 创建工作簿
        const workbook = createWorkBook();
        // 2. 创建表格
        initWorkBook(workbook, luckysheet);
      }

      async function initWorkBook(workbook, luckysheet) {
        let luckysheetData = luckysheet.getluckysheetfile();
        luckysheetData.forEach((sheet, sheetid) => {
          if (sheet.data.length === 0) return true;
          const worksheet = workbook.addWorksheet(sheet.name);
          setStyleAndValue(sheet.data, worksheet, sheetid);
          setMerge(sheet.config.merge, worksheet);
          setBorder(sheet.config.borderInfo, worksheet);
          return true;
        }); // 4.写入 buffer

        workbook.xlsx
          .writeBuffer()
          .then((res) => {
            let data1 = arrayBufferToBase64(res);
            uni.postMessage({
              data: {
                type: "data",
                xlsxdata: data1,
              },
            });
          })
          .catch((err) => {
            alert(err);
          });
      }

      function createWorkBook() {
        const workbook = new ExcelJS.Workbook();
        workbook.creator = "wanui";
        workbook.lastModifiedBy = "wanui";
        workbook.created = new Date();
        workbook.modified = new Date();

        workbook.properties.date1904 = true;

        return workbook;
      }

      function setMerge(luckyMerge = {}, worksheet) {
        const mergearr = Object.values(luckyMerge);
        mergearr.forEach(function (elem) {
          // elem格式：{r: 0, c: 0, rs: 1, cs: 2}
          // 按开始行，开始列，结束行，结束列合并（相当于 K10:M12）
          worksheet.mergeCells(
            elem.r + 1,
            elem.c + 1,
            elem.r + elem.rs,
            elem.c + elem.cs
          );
        });
      }

      function setBorder(luckyBorderInfo, worksheet) {
        if (!Array.isArray(luckyBorderInfo)) return;
        luckyBorderInfo.forEach(function (elem) {
          let border = borderConvert(elem);
          // let rang = elem.range[0];
          // console.log(rang.column_focus + 1, rang.row_focus + 1)
          // worksheet.getCell(border.row_value, border.col_value).border = border;
          worksheet.getCell(border.row_index + 1, border.col_index + 1).border =
            border;
        });
      }

      function setStyleAndValue(cellArr, worksheet, sheetid) {
        if (!Array.isArray(cellArr)) return;
        cellArr.forEach(function (row, rowid) {
          row.every(function (cell, columnid) {
            if (!cell) return true;
            let fill = fillConvert(cell.bg);
            let font = fontConvert(
              cell.ff,
              cell.fc,
              cell.bl,
              cell.it,
              cell.fs,
              cell.cl,
              cell.ul
            );
            let alignment = alignmentConvert(
              cell.vt,
              cell.ht,
              cell.tb,
              cell.tr
            );
            let value;
            if (cell.f) {
              value = { formula: cell.f, result: cell.v };
            } else {
              value = cell.v;
            }
            let target = worksheet.getCell(rowid + 1, columnid + 1);
            target.fill = fill;
            target.font = font;
            target.alignment = alignment;
            target.value = value;
            if (sheetid == 3 && row == 1 && cell == 0) {
              console.log(value, "第二行， 第一列");
            }
            return true;
          });
        });
      }

      function fillConvert(bg) {
        if (!bg) {
          return {};
        }
        let fill = {
          type: "pattern",
          pattern: "solid",
          fgColor: { argb: bg.replace("#", "") },
        };
        return fill;
      }

      function fontConvert(
        ff = 0,
        fc = "#000000",
        bl = 0,
        it = 0,
        fs = 10,
        cl = 0,
        ul = 0
      ) {
        // luckysheet：ff(样式), fc(颜色), bl(粗体), it(斜体), fs(大小), cl(删除线), ul(下划线)
        const luckyToExcel = {
          0: "微软雅黑",
          1: "宋体（Song）",
          2: "黑体（ST Heiti）",
          3: "楷体（ST Kaiti）",
          4: "仿宋（ST FangSong）",
          5: "新宋体（ST Song）",
          6: "华文新魏",
          7: "华文行楷",
          8: "华文隶书",
          9: "Arial",
          10: "Times New Roman ",
          11: "Tahoma ",
          12: "Verdana",
          num2bl: function (num) {
            return num === 0 ? false : true;
          },
        };

        let font = {
          name: luckyToExcel[ff],
          family: 1,
          size: fs,
          color: { argb: fc.replace("#", "") },
          bold: luckyToExcel.num2bl(bl),
          italic: luckyToExcel.num2bl(it),
          underline: luckyToExcel.num2bl(ul),
          strike: luckyToExcel.num2bl(cl),
        };

        return font;
      }

      function alignmentConvert(
        vt = "default",
        ht = "default",
        tb = "default",
        tr = "default"
      ) {
        // luckysheet:vt(垂直), ht(水平), tb(换行), tr(旋转)
        const luckyToExcel = {
          vertical: {
            0: "middle",
            1: "top",
            2: "bottom",
            default: "top",
          },
          horizontal: {
            0: "center",
            1: "left",
            2: "right",
            default: "left",
          },
          wrapText: {
            0: false,
            1: false,
            2: true,
            default: false,
          },
          textRotation: {
            0: 0,
            1: 45,
            2: -45,
            3: "vertical",
            4: 90,
            5: -90,
            default: 0,
          },
        };

        let alignment = {
          vertical: luckyToExcel.vertical[vt],
          horizontal: luckyToExcel.horizontal[ht],
          wrapText: luckyToExcel.wrapText[tb],
          textRotation: luckyToExcel.textRotation[tr],
        };
        return alignment;
      }

      function handlerRange(borderValue) {
        debugger;
        // {borderType, style, color, range}
        let borderType = borderValue.borderType;
        let style = borderValue.style;
        return {};
      }

      function handlerCell(borderValue) {
        let borderObj = {};
        Object.keys(borderValue).forEach((key) => {
          let borderConfig = LuckysheetMapper.border;
          let pos = borderConfig.positionMapper[key];
          let keyValue = borderValue[key];
          if (pos) {
            borderObj[pos] = {
              style: borderConfig.styleMapper[keyValue.style],
              color: keyValue.color || "",
            };
          } else {
            borderObj[key] = keyValue;
          }
        });
        return borderObj;
      }

      function borderConvert(elem) {
        // 对应luckysheet的config中borderinfo的的参数
        let { rangeType, value } = elem;
        switch (rangeType) {
          case "cell":
            return handlerCell(value);
          case "range":
            return handlerRange(value);
        }
      }
    </script>
    <script>
      let cancelBtn = document.getElementById("cancel");
      let saveBtn = document.getElementById("save");
      cancelBtn.addEventListener("click", () => {
        uni.postMessage({
          data: {
            type: "cancel",
          },
        });
      });
      saveBtn.addEventListener("click", () => {
        uni.postMessage({
          data: {
            type: "save",
          },
        });
      });
    </script>
  </body>
</html>
